package com.smallA.association.service.Impl;

import com.smallA.association.bo.DepartmentData;
import com.smallA.association.bo.Result;
import com.smallA.association.bo.ResultAssociation;
import com.smallA.association.bo.ResultAssociationDepartment;
import com.smallA.association.constant.DataConstant;
import com.smallA.association.constant.UserConstant;
import com.smallA.association.mapper.AssociationMapper;
import com.smallA.association.mapper.DepartmentMapper;
import com.smallA.association.mapper.PhotoWallMapper;
import com.smallA.association.mapper.UserMapper;
import com.smallA.association.pojo.Association;
import com.smallA.association.pojo.Client;
import com.smallA.association.pojo.Department;
import com.smallA.association.service.AssociationService;
import com.smallA.association.utils.DataUtils;
import com.smallA.association.utils.FileUploadUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author wanda
 * 社团业务逻辑接口实现类
 */
@Service
public class AssociationServiceImpl implements AssociationService {

    private static final String IMG_PATH = "/home/JavaProject/ImgFile";
    //private static final String IMG_PATH = "C:\\Users\\wanda\\Desktop\\test";

    @Resource
    AssociationMapper associationMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    DepartmentMapper departmentMapper;
    @Resource
    PhotoWallMapper photoWallMapper;

    @Override
    public Result<ResultAssociationDepartment> updateAssociation(Association association, MultipartFile head, MultipartFile QRCode) {
        // 先对数据校验一下
        if (!DataUtils.examineNumber(association.getId())) {
            return new Result<>(DataConstant.UPDATE_ASSOCIATION_DATA_FAIL, DataConstant.MSG_BAD_REQUEST);
        }
        // 校验下要修改的手机号是否有问题
        if (association.getTeacherPhone() != null && DataUtils.examinePhone(association.getTeacherPhone())) {
            return new Result<>(DataConstant.UPDATE_ASSOCIATION_DATA_FAIL, DataConstant.MSG_BAD_REQUEST);
        }
        if (association.getAssociationStudentPhone() != null && DataUtils.examinePhone(association.getAssociationStudentPhone())) {
            return new Result<>(DataConstant.UPDATE_ASSOCIATION_DATA_FAIL, DataConstant.MSG_BAD_REQUEST);
        }
        if (head != null) {
            // 这个没问题就校验下然后上传
            String fileName = head.getOriginalFilename();
            if (fileName != null && !"".equalsIgnoreCase(fileName.trim()) && FileUploadUtils.isImageFile(fileName)) {
                // 校验过了之后就上传了
                String headName = "head_" + association.getId().toString() + FileUploadUtils.getFileType(fileName);
                if (FileUploadUtils.fileUpload(head, IMG_PATH, headName) != null) {
                    // 没问题就添加文件
                    association.setAssociationHead("/ImgFile/" + headName);
                }
            }
        }
        if (QRCode != null) {
            // 这个没问题就校验下然后上传
            String fileName = QRCode.getOriginalFilename();
            if (fileName != null && !"".equalsIgnoreCase(fileName.trim()) && FileUploadUtils.isImageFile(fileName)) {
                // 校验过了之后就上传了
                String codeName = "QRCode_" + association.getId().toString() + FileUploadUtils.getFileType(fileName);
                if (FileUploadUtils.fileUpload(QRCode, IMG_PATH, codeName) != null) {
                    // 没问题就添加文件
                    association.setQrCode("/ImgFile/" + codeName);
                }
            }
        }
        if (associationMapper.updateByAssociation(association) > 0) {
            // 这个修改成功之后就来判断下操作了
            List<String> departments = association.getDepartments();
            // 遍历获取
            for (String name : departments) {
                // 编辑下名字
                if (DataUtils.examineStr(name, 50)) {
                    // 没问题就添加
                    departmentMapper.registerByDepartment(name, association.getId());
                }
            }
            Association successAssociation = associationMapper.selectById(association.getId());
            List<Department> departmentsList = departmentMapper.selectByAid(successAssociation.getId());
            List<DepartmentData> list = new ArrayList<>();
            for (Department department : departmentsList) {
                list.add(new DepartmentData(department, 0, 0));
            }
            return new Result<ResultAssociationDepartment>(new ResultAssociationDepartment(successAssociation, list), DataConstant.UPDATE_ASSOCIATION_DATA_SUCCESS);
        }
        return new Result<>(DataConstant.UPDATE_ASSOCIATION_DATA_FAIL, DataConstant.MSG_BAD_REQUEST);
    }

    @Override
    public Result<Association> selectById(Integer id) {
        if (DataUtils.examineNumber(id)) {
            Association association = associationMapper.selectById(id);
            if (association != null) {
                return new Result<Association>(association);
            }
        }
        return new Result<>(DataConstant.MSG_CODE_BAD_REQUEST, DataConstant.MSG_BAD_REQUEST);
    }

    private void addAssociationInList(List<Association> A, List<ResultAssociation> list, Integer state) {
        for (Association association : A) {
            list.add(new ResultAssociation(association, state));
        }
    }

    @Override
    public Object getUserData(Client user, Integer typeRole) {
        if (user != null && DataUtils.examineNumber(user.getId(), typeRole)) {
            if (typeRole == UserConstant.ROLE_ASSOCIATION_ID) {
                // 判断是一个社团用户, 填充数据
                Association association = associationMapper.selectByUserId(user.getId());
                List<DepartmentData> list = new ArrayList<>();
                List<Department> departments = departmentMapper.selectByAid(association.getId());
                // 再统计下各个部门的人数
                for (Department department : departments) {
                    // 遍历开始
                    DepartmentData data = new DepartmentData(department,
                            departmentMapper.selectApplyNum(department.getId()),
                            departmentMapper.selectApplyNumByStatus(department.getId(), 2));
                    list.add(data);
                }
                return new ResultAssociationDepartment(association, list);
            } else if (typeRole == UserConstant.ROLE_MANAGER_ID) {
                List<ResultAssociation> res = new ArrayList<>();
                addAssociationInList(associationMapper.selectAllAssociation(UserConstant.STATE_REGISTER), res, UserConstant.STATE_REGISTER);
                addAssociationInList(associationMapper.selectAllAssociation(UserConstant.STATE_NORMAL), res, UserConstant.STATE_NORMAL);
                addAssociationInList(associationMapper.selectAllAssociation(UserConstant.STATE_BANING), res, UserConstant.STATE_BANING);
                if (!res.isEmpty()) {
                    return res;
                }
            }
        }
        return null;
    }

    @Override
    public Result<Object> updateByDepartment(Department department) {
        if (department == null || !DataUtils.examineNumber(department.getId())) {
            return new Result<>(DataConstant.UPDATE_DEPARTMENT_FAIL, DataConstant.MSG_BAD_REQUEST);
        }
        // 调用接口修改即可
        if (departmentMapper.updateByDepartment(department) <= 0) {
            return new Result<>(DataConstant.UPDATE_DEPARTMENT_FAIL, DataConstant.MSG_BAD_REQUEST);
        }
        department = departmentMapper.selectById(department.getId());
        return new Result<>(department, DataConstant.UPDATE_DEPARTMENT_SUCCESS);
    }

    @Override
    public Result<Object> uploadPhotoWall(MultipartFile[] files, Integer aid, Integer[] ids) {
        if (aid == null) {
            return new Result<>(DataConstant.UPLOAD_PHOTO_FAIL, DataConstant.MSG_BAD_REQUEST);
        }
        // 这里查询社团校验下是否存在这个社团
        Association association = associationMapper.selectById(aid);
        if (association == null) {
            return new Result<>(DataConstant.UPLOAD_PHOTO_FAIL, DataConstant.MSG_BAD_REQUEST);
        }
        // 没问题就遍历获取集合
        for (MultipartFile file : files) {
            // 先对文件进行校验
            String fileName = file.getOriginalFilename();
            if (fileName != null && !"".equalsIgnoreCase(fileName.trim()) && FileUploadUtils.isImageFile(fileName)) {
                // 这个没问题才上传
                // 因为已经校验过文件有没有问题了, 所以这里直接UUID + 拼接文件名
                String name = UUID.randomUUID().toString() + FileUploadUtils.getFileType(fileName);
                String filePath = FileUploadUtils.fileUpload(file, IMG_PATH, UUID.randomUUID().toString() + FileUploadUtils.getFileType(fileName));
                // 获取上传的文件的路径, 上传到照片墙的那啥
                photoWallMapper.insertPhoto(aid, "/ImgFile/" + name);
            }
        }
        for (Integer id : ids) {
            // 遍历删除对应的照片
            photoWallMapper.updatePhotoStatus(id);
        }
        // 查询下所有现在这个社团名下的然后返回即可
        return new Result<>(photoWallMapper.selectPhotosByAid(aid), DataConstant.UPLOAD_PHOTO_SUCCESS);
    }

    @Override
    public Result<Object> selectPhotoWall(Association association) {
        if (association == null || !DataUtils.examineNumber(association.getId())) {
            return new Result<>(DataConstant.UPLOAD_PHOTO_FAIL, DataConstant.MSG_BAD_REQUEST);
        }
        return new Result<>(photoWallMapper.selectPhotosByAid(association.getId()), DataConstant.UPLOAD_PHOTO_SUCCESS);
    }

    @Override
    public Result<Object> selectDepartment(Department dep) {
        if (dep == null || dep.getId() == null) {
            return new Result<>(DataConstant.SELECT_DEPARTMENT_FAIL, DataConstant.MSG_BAD_REQUEST);
        }
        Department department = departmentMapper.selectById(dep.getId());
        // 获取了部门之后就查询下报名的
        if (department == null) {
            return new Result<>(DataConstant.SELECT_DEPARTMENT_FAIL, DataConstant.MSG_BAD_REQUEST);
        }
        return new Result<>(new DepartmentData(department,
                departmentMapper.selectApplyNum(dep.getId()),
                departmentMapper.selectApplyNumByStatus(dep.getId(), 2)), DataConstant.SELECT_DEPARTMENT_SUCCESS);
    }

    @Override
    public Result<Object> selectByUser(Client user) {
        Client client = userMapper.findByName(user.getUsername());
        System.out.println(client);
        System.out.println(user);
        Object data = getUserData(user, client.getRole().getId());
        if (data != null) {
            return new Result<>(data);
        } else {
            return new Result<>(DataConstant.MSG_CODE_BAD_REQUEST, DataConstant.MSG_BAD_REQUEST);
        }
    }


}
